package com.itljm.cxrMarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itljm.cxrMarket.entity.LoginUser;
import com.itljm.cxrMarket.entity.SysUser;
import com.itljm.cxrMarket.entity.dto.MenuDto;
import com.itljm.cxrMarket.entity.SysMenu;
import com.itljm.cxrMarket.mapper.SysMenuPermissionMapper;
import com.itljm.cxrMarket.mapper.SysRolePermissionMapper;
import com.itljm.cxrMarket.mapper.SysUserRoleMapper;
import com.itljm.cxrMarket.service.SysMenuService;
import com.itljm.cxrMarket.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Autowired
    private SysMenuPermissionMapper sysMenuPermissionMapper;

    @Override
    public List<SysMenu> queryMenuAll() {
        List<SysMenu> list = sysMenuMapper.selectList(new QueryWrapper<>());
        return list;
    }

    @Override
    public Map<String, Object> buildTree(List<MenuDto> menus) {
        List<MenuDto> trees = new ArrayList<>();
        Set<Integer> ids = new HashSet<>();

        for (MenuDto menu : menus) {
            if (menu.getParentId() == 0){
                trees.add(menu);
            }
            for (MenuDto m : menus) {
                if (m.getParentId().equals(menu.getId())){
                    if (menu.getChildren() == null){
                        menu.setChildren(new ArrayList<>());
                    }
                    menu.getChildren().add(m);
                    ids.add(m.getId());
                }
            }
        }
        Map<String, Object> map = new HashMap<>(2);
        if (trees.size() == 0){
            trees = menus.stream().filter(s -> !ids.contains(s.getId())).collect(Collectors.toList());
        }
        map.put("content",trees);
        map.put("total", menus.size());
        return map;
    }

    @Override
    public List<SysMenu> generateDynamicMenu() {
        // 通过SecurityContextHolder获取当前用户的认证信息
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        // 获取用户的角色ID列表
        List<Long> roleIds = sysUserRoleMapper.selectRoleIdsByUserId(userId);

        // 获取角色对应的权限ID列表
        List<Long> permissionIds = sysRolePermissionMapper.selectPermissionIdsByRoleIds(roleIds);

        // 获取有权限的菜单项ID列表
        List<Long> menuIds = sysMenuPermissionMapper.selectMenuIdsByPermissionIds(permissionIds);
        if (menuIds == null || menuIds.isEmpty()) {
            return Collections.emptyList(); // 修复空指针或空列表导致的异常
        }

        // 根据菜单项ID获取菜单详情
        List<SysMenu> menus = sysMenuMapper.selectMenusByIds(menuIds);

        // 构建树状结构
        return buildMenuTree(menus);
    }

    private List<SysMenu> buildMenuTree(List<SysMenu> allMenus) {
        List<SysMenu> rootMenus = new ArrayList<>();
        for (SysMenu menu : allMenus) {
            if (menu.getParentId() == null || menu.getParentId() == 0) {
                rootMenus.add(menu);
            }
        }

        for (SysMenu menu : rootMenus) {
            menu.setChildren(getChildMenus(allMenus, menu.getId()));
        }

        return rootMenus;
    }

    private List<SysMenu> getChildMenus(List<SysMenu> allMenus, Integer parentId) {
        List<SysMenu> childMenus = new ArrayList<>();
        for (SysMenu menu : allMenus) {
            if (menu.getParentId() != null && menu.getParentId().equals(parentId)) {
                childMenus.add(menu);
            }
        }

        for (SysMenu menu : childMenus) {
            menu.setChildren(getChildMenus(allMenus, menu.getId()));
        }

        return childMenus;
    }

}




